package meterMonitor.service;


import meterMonitor.mapper.SysUsersMapper;
import meterMonitor.model.SysUsersPO;
import meterMonitor.util.Sha256;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.sql.Timestamp;
import java.util.List;

@Service
@Transactional
public class SysUsersService {

    private final static Logger logger = LoggerFactory.getLogger(SysUsersService.class);


    @Autowired
    private SysUsersMapper sysUsersMapper;

    public void addSysUsers(SysUsersPO sysUsers) {
        // 校验用户名
        validateUserName(sysUsers.getUserName());
        // 加密
        sysUsers.setUserPwd(Sha256.getSHA256(sysUsers.getUserPwd()));
        sysUsers.setCreateTime(new Timestamp(System.currentTimeMillis()));
        sysUsers.setState(1); // 默认在职
        sysUsersMapper.add(sysUsers);
    }

    public void updateSysUsers(SysUsersPO sysUsers) {
        // 校验用户名
        //validateUserName(sysUsers.getUserName());
        // 加密
        if (sysUsers.getUserPwd() != null) {
            sysUsers.setUserPwd(Sha256.getSHA256(sysUsers.getUserPwd()));
        }
        sysUsers.setCreateTime(new Timestamp(System.currentTimeMillis()));
        sysUsersMapper.update(sysUsers);
    }


    public void deleteSysUsersById(int userId) {
        SysUsersPO param = new SysUsersPO();
        param.setUserId(userId);
        sysUsersMapper.delete(param);
        param = null;
    }

    public List<SysUsersPO> queryList(SysUsersPO sysUsers) {
        return sysUsersMapper.query(sysUsers);
    }

    public SysUsersPO getSysUsersById(int userId) {
        SysUsersPO param = new SysUsersPO();
        param.setUserId(userId);
        List<SysUsersPO> sysUsers = queryList(param);
        param = null;
        if (CollectionUtils.isEmpty(sysUsers)) {
            throw new NullPointerException();
        } else {
            return sysUsers.get(0);
        }
    }

    public void validateUserName(String userName) {
        SysUsersPO param = new SysUsersPO();
        param.setUserName(userName);

        List<SysUsersPO> sysUsers = queryList(param);
        if (CollectionUtils.isEmpty(sysUsers)) {
            logger.info("用户名唯一性校验通过!");
        } else {
            throw new IllegalArgumentException("用户名已经存在！");
        }

    }

    public SysUsersPO getUser(SysUsersPO sysUsers) {
        return sysUsersMapper.getUser(sysUsers.getUserName());
    }

    public SysUsersPO getUserByName(String userName) {
        return sysUsersMapper.getUser(userName);
    }
}
